var Sequelize = require('sequelize');
var sequelize = require('../../../core/sequlize_pool').sequelize;
var models = require('../../models');
var userDao = module.exports;

userDao.createUser = async function(user) {
    return models.admin.AdminUser.create(user);
};

userDao.updateUser = async function(user) {
    return models.admin.AdminUser.update(user, {
        where: {
            id: user.id
        }
    });
};

userDao.getUserById = async function (userId){
    return models.admin.AdminUser.findOne({
        where: {
            id: userId,
            is_del: 0
        }
    });
};

userDao.getUserByUserName = async function (username){
    return models.admin.AdminUser.findOne({
        where: {
            user_name: username,
            is_del: 0
        }
    });
};

userDao.getUsers = async function (name, username, offset, limit) {
    var or = [];
    if (name && name.length != 0){
        or.push({
            name: {
                [Sequelize.Op.like]: '%'+name+'%'
            }
        });
    }

    if (username && username.length != 0){
        or.push({
            user_name: {
                [Sequelize.Op.like]: '%'+username+'%'
            }
        });
    }

    var where = {is_del: 0};
    if (or.length != 0){
        where = {is_del: 0, [Sequelize.Op.or] : or};
    }

    return models.admin.AdminUser.findAndCountAll({
        where: where,
        offset: Number(offset),
        limit: Number(limit),
    });
};

userDao.destroyUsers = async function (user_ids){
    return models.admin.AdminUser.destroyUsers(user_ids);
};

userDao.setUserRoles = async function (user_id, role_ids){
    const user = await models.admin.AdminUser.findOne({
        where: {
            id: user_id,
            is_del: 0
        }
    });
    const roles = await models.admin.AdminRole.findAll({
        where: {
            role_id: role_ids,
            is_del: 0
        }
    });
    return user.setUserRoles(roles);
};

userDao.getUserRoles = async function (user_id) {
    const user = await models.admin.AdminUser.findOne({
        where: {
            id: user_id,
            is_del: 0
        }
    });
    return user.getUserRoles();
};

userDao.getMyMenus = async function (user_id) {
    var sql = "SELECT menu.* FROM system_menu AS menu INNER JOIN system_menu_role AS menu_role " +
              "ON menu.menu_id = menu_role.menu_id AND " +
              "menu_role.role_id IN (SELECT role_id FROM system_user_role WHERE user_id = $user_id) " +
              "AND menu.is_del = 0 GROUP BY menu.menu_id";
    return sequelize.query(sql, {
        bind: { user_id: user_id },
        type: sequelize.QueryTypes.SELECT,
        model: models.admin.AdminMenu
    });
};

